//
// @author 风杨
// @date 22-9-26 下午5:16
// @see <a href="yueny09@163.com">mailTo: yueny09@163.com</a>
//

use mysql::prelude::*;
use mysql::*;
use log::*;
use crate::get_jdbc_url;

pub fn mysql_conn_test() {
    info!(target:"", "################ mysql_conn_test ###################");
    let query_sql = String::from("Select * from time_zone_transition limit 5");

    //设置连接字符串
    let url = get_jdbc_url();

    //创建连接池, 21-是直接传url 字符串即可, 21+ 要求必须为opts类型
    // // 21-
    // let pool = Pool::new(&url).unwrap();
    // 21+
    let ops = Opts::from_url(&url).unwrap();
    let pool = Pool::new(ops).unwrap();

    //连接数据库
    let mut conn = pool.get_conn().unwrap();

    //数据库操作
    //1.查询 time_zone_transition 表
    //方式1：流式查询  数据逐行读取，数据不会存储在内存中
    conn.query_iter(&query_sql)
        .unwrap()
        .for_each(|row| {
            let r: (i32, String, i32) = from_row(row.unwrap());
            println!(
                "STREAM: Time_zone_id={},Transition_time={},Transition_type_id={}",
                r.0, r.1, r.2
            );
        });

    //方式2：将数据集取出存储在Vec中
    let res: Vec<(i32, String, i32)> = conn.query(&query_sql).unwrap();
    for r in res {
        println!(
            "Vec: Time_zone_id={},Transition_time={},Transition_type_id={}",
            r.0, r.1, r.2
        );
    }

    //方式3：将数据转换成 Struct
    struct TimeZoneTransition {
        id: i32,
        time: i64,
        typeId: i32,
    }

    let res = conn
        .query_map(
            query_sql,
            | (id, time, typeId)| TimeZoneTransition { id, time, typeId },
        )
        .expect("QUERY FAILED");

    for item in res {
        println!(
            "Struct: id={},time={},typeId={}",
            item.id, item.time, item.typeId
        );
    }
}